package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.*;
import cc.rengu.igas.momp.common.dao.impl.*;
import cc.rengu.igas.momp.common.entity.TMMcCashierCashbackInfo;
import cc.rengu.igas.momp.common.entity.TMMcMchntInfo;
import cc.rengu.igas.momp.common.entity.TMPlatBizTmp;
import cc.rengu.igas.momp.common.enums.*;
import cc.rengu.igas.momp.common.util.CommonMessageCheck;
import cc.rengu.igas.momp.common.util.MompDateUtil;
import cc.rengu.igas.momp.common.util.MompToolUtil;
import cc.rengu.igas.momp.common.util.RbdpClient;
import cc.rengu.igas.momp.facade.request.ManageCashierCashbackMcRequest;
import cc.rengu.igas.momp.facade.response.ManageCashierCashbackMcResponse;
import cc.rengu.jrbdp.register.realtime.client.RealTimeRegisterClient;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.*;
import cc.rengu.utility.base.StringUtil;
import cc.rengu.utility.dbs.Database;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 收银员返现类活动信息管理功能实现
 *
 * @author Jinan Liu
 * @version 1.0.0
 * @date 2020/4/2 17:45
 */
public class ManageCashierCashbackMcService extends RadpService {

    private String globalTimeStamp;
    private String globalOprId;
    private String globalTableName = TableNameEnum.T_M_MC_CCB_INFO.getTableNameCode();
    /**
     * 批量任务注册参数类型 PARAM_TYPE
     */
    private static final String MOMP_RBDP_ADDRESS = "MOMP_RBDP_ADDRESS";
    /**
     * 批量任务注册地址参数键值 PARAM_KEY
     */
    private static final String MOMP_RBDP_REGISTER_ADDRESS = "MOMP_RBDP_REGISTER_ADDRESS";
    /**
     * 当前日期
     */
    private String globalTxnDate;

    @Override
    protected int bizInit(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizProcess(String s, int i) {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        try {
            ManageCashierCashbackMcRequest manageCashierCashbackMcRequest = new ManageCashierCashbackMcRequest();
            ConvertUtil.convertOutput(manageCashierCashbackMcRequest);

            ManageCashierCashbackMcResponse manageCashierCashbackMcResponse = new ManageCashierCashbackMcResponse();
            manageCashierCashbackMcResponse.setHeader(manageCashierCashbackMcRequest.getHeader());
            BizResponse<ManageCashierCashbackMcResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(manageCashierCashbackMcResponse);

            // 判断查询类型
            rglog.debug("TXN_NUM=<{}>", manageCashierCashbackMcRequest.getHeader().getTxnNum());

            String queryType = manageCashierCashbackMcRequest.getQueryType();
            String queryRole = manageCashierCashbackMcRequest.getQueryRole();
            String oprType = manageCashierCashbackMcRequest.getOprType();
            globalTimeStamp = new SimpleDateFormat(CommonConstant.TIMESTAMP_FORMAT).format(new Date());
            globalOprId = manageCashierCashbackMcRequest.getQueryId();
            globalTxnDate = manageCashierCashbackMcRequest.getHeader().getTransDate();

            rglog.debug("QUERY_TYPE=<{}>", queryType);
            rglog.debug("QUERY_ROLE=<{}>", queryRole);
            rglog.debug("OPR_TYPE=<{}>", oprType);

            /* 报文检查 */
            CommonMessageCheck.checkBizMessageHeader(queryType, globalOprId, queryRole, rglog);
            CommonMessageCheck.checkSingleValue(oprType, rglog);

            // 服务调用
            BizResponse<ManageCashierCashbackMcResponse> bizResponseNew = manageCashierCashbackMc(
                    manageCashierCashbackMcRequest, manageCashierCashbackMcResponse, xmlTreeUtil);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    /**
     * 收银员返现类活动管理
     *
     * @param manageCashierCashbackMcRequest  收银员返现类营销活动管理接口请求对象
     * @param manageCashierCashbackMcResponse 收银员返现类营销活动管理接口应答对象
     * @param xmlTreeUtil                     内部XML树
     * @return cc.rengu.oltp.service.model.BizResponse<cc.rengu.igas.momp.facade.response.ManageCashierCashbackMcResponse> 收银员返现类营销活动管理接口应答对象
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/29 01:38
     */
    private BizResponse<ManageCashierCashbackMcResponse> manageCashierCashbackMc(ManageCashierCashbackMcRequest manageCashierCashbackMcRequest, ManageCashierCashbackMcResponse manageCashierCashbackMcResponse, XmlTreeUtil xmlTreeUtil)
            throws Exception {

        BizResponse<ManageCashierCashbackMcResponse> bizResponse = new BizResponse<>();

        /* 判断查询类型 */
        String queryType = manageCashierCashbackMcRequest.getQueryType();
        String queryRole = manageCashierCashbackMcRequest.getQueryRole();
        String oprType = manageCashierCashbackMcRequest.getOprType();

        /* 判断用户的角色和权限 */
        if (QueryTypeEnum.BANK_QUERY_TYPE.getQueryTypeCode().equals(queryType)) {
            if (QueryRoleEnum.BANK_AUDIT_QYERY_ROLE.getQueryRoleCode().equals(queryRole)) {
                // 银行审批岗-正式表和临时表所有数据
                if (OprTypeEnum.AUDIT_PASSED.getOprTypeCode().equals(oprType)) {
                    // 审批通过
                    auditPassed(manageCashierCashbackMcRequest);

                } else if (OprTypeEnum.AUDIT_REFUSED.getOprTypeCode().equals(oprType)) {
                    // 审批拒绝
                    auditRefused(manageCashierCashbackMcRequest);

                } else {
                    rglog.error("当前<{}>角色的查询用户<{}>无权限查看数据!", queryRole, queryType);
                    throw new BizException(RespCodeEnum.NOT_SUPPORTED_OPR_TYPE_ERROR.getRespCode(), RespCodeEnum.NOT_SUPPORTED_OPR_TYPE_ERROR.getRespDesc());
                }

            } else if (QueryRoleEnum.BANK_BASIC_QUERY_ROLE.getQueryRoleCode().equals(queryRole)) {
                if (OprTypeEnum.AUDIT_DELETE.getOprTypeCode().equals(oprType)) {
                    /* 删除草稿 */
                    deleteDraftMcData(manageCashierCashbackMcRequest);
                }
            } else {
                //银行录入岗或银行发布岗
                rglog.error("当前<{}>角色的查询用户<{}>无权限查看数据!", queryRole, queryType);
                throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespDesc());
            }
        } else {
            // 商户、代理商、收银员或用户
            rglog.error("当前<{}>角色的查询用户<{}>无权限查看数据!", queryRole, queryType);
            throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespDesc());
        }


        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        manageCashierCashbackMcResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        manageCashierCashbackMcResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(manageCashierCashbackMcResponse);

        return bizResponse;
    }

    /**
     * 删除草稿
     *
     * @param manageCashierCashbackMcRequest 收银员返现类营销活动管理接口请求对象
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/4/7 00:53
     */
    private void deleteDraftMcData(ManageCashierCashbackMcRequest manageCashierCashbackMcRequest) throws Exception {
        int returnCode = 0;
        String instId = manageCashierCashbackMcRequest.getHeader().getInstId();
        String mcNo = manageCashierCashbackMcRequest.getMcNo();
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        // 查询营销活动信息
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        TMMcCashierCashbackInfo tmMcCashierCashbackInfo = (TMMcCashierCashbackInfo) mcDetailInfoMapper.selectMcDetailInfo(instId, mcNo, TableNameEnum.T_M_MC_CCB_INFO.getTableNameCode());

        if (null == tmMcCashierCashbackInfo) {
            // 获取营销活动信息失败
            rglog.error("获取营销活动信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, mcNo);
            throw new BizException(RespCodeEnum.GET_MONEY_OFF_MC_DETAIL_ERROR.getRespCode(), RespCodeEnum.GET_MONEY_OFF_MC_DETAIL_ERROR.getRespDesc());
        }

        if (!McStatusEnum.DRAFT.getMcStatusCode().equals(tmMcCashierCashbackInfo.getMcStatus())) {
            // 营销活动状态异常，不可删除草稿
            rglog.error("{}}, MC_STATUS=<{}>, MC_NO=<{}>", RespCodeEnum.WRONG_MC_STATUS_TO_DELETE_DRAFT_ERROR.getRespDesc(), tmMcCashierCashbackInfo.getMcStatus(), mcNo);
            throw new BizException(RespCodeEnum.WRONG_MC_STATUS_TO_DELETE_DRAFT_ERROR.getRespCode(), RespCodeEnum.WRONG_MC_STATUS_TO_DELETE_DRAFT_ERROR.getRespDesc());
        }

        if (AuditStatusEnum.NEW_AUDIT_PROCESSING.getAuditStatusCode().equals(tmMcCashierCashbackInfo.getAuditStatus()) ||
                AuditStatusEnum.MODIFY_AUDIT_PROCESSING.getAuditStatusCode().equals(tmMcCashierCashbackInfo.getAuditStatus()) ||
                AuditStatusEnum.PUBLISH_AUDIT_PROCESSING.getAuditStatusCode().equals(tmMcCashierCashbackInfo.getAuditStatus())) {
            // 审批中不可删除草稿
            rglog.error("{}}, MC_STATUS=<{}>, MC_NO=<{}>", RespCodeEnum.WRONG_MC_STATUS_TO_DELETE_DRAFT_ERROR.getRespDesc(), tmMcCashierCashbackInfo.getMcStatus(), mcNo);
            throw new BizException(RespCodeEnum.WRONG_MC_STATUS_TO_DELETE_DRAFT_ERROR.getRespCode(), RespCodeEnum.WRONG_MC_STATUS_TO_DELETE_DRAFT_ERROR.getRespDesc());
        }

        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        // 删除营销活动信息
        returnCode = mcDetailInfoMapper.deleteCashierCashbackMcInfo(instId, mcNo);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DELETE_MC_DATA_ERROR.getRespDesc(), returnCode, mcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DELETE_MC_DATA_ERROR.getRespCode(), RespCodeEnum.DELETE_MC_DATA_ERROR.getRespDesc());
        }

        // 删除营销活动机构信息
        McOrgInfoMapper mcOrgInfoMapper = new McOrgInfoMapperImpl();
        returnCode = mcOrgInfoMapper.deleteMcOrgInfoListByBank(instId, mcNo);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DELETE_MC_ORG_DATA_ERROR.getRespDesc(), returnCode, mcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DELETE_MC_ORG_DATA_ERROR.getRespCode(), RespCodeEnum.DELETE_MC_ORG_DATA_ERROR.getRespDesc());
        }

        // 删除营销活动商户信息
        McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
        returnCode = mcMchntInfoMapper.deleteMcMchntInfoListByBank(instId, mcNo);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DELETE_MC_MCHNT_DATA_ERROR.getRespDesc(), returnCode, mcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DELETE_MC_MCHNT_DATA_ERROR.getRespCode(), RespCodeEnum.DELETE_MC_MCHNT_DATA_ERROR.getRespDesc());
        }

        // 删除营销活动规则信息
        McRuleInfoMapper mcRuleInfoMapper = new McRuleInfoMapperImpl();
        returnCode = mcRuleInfoMapper.deleteCashierCashbackRuleInfoListByMcNo(instId, mcNo);//deleteMoneyOffRuleInfoListByBank
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DELETE_MC_RULE_DATA_ERROR.getRespDesc(), returnCode, mcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DELETE_MC_RULE_DATA_ERROR.getRespCode(), RespCodeEnum.DELETE_MC_RULE_DATA_ERROR.getRespDesc());
        }

        // 删除营销活动产品信息
        McProductInfoMapper mcProductInfoMapper = new McProductInfoMapperImpl();
        returnCode = mcProductInfoMapper.deleteMcProductInfoListByBank(instId, mcNo);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DELETE_MC_PRODUCT_DATA_ERROR.getRespDesc(), returnCode, mcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DELETE_MC_PRODUCT_DATA_ERROR.getRespCode(), RespCodeEnum.DELETE_MC_PRODUCT_DATA_ERROR.getRespDesc());
        }

        //开启oltp数据库事务
        /* 开启数据库事务 */
        String dbPoolNames = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.OLTP_POOL_NAME);
        String corporations = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporations && !corporations.isEmpty()) {
            String dbPoolCashNode = corporations.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolNames = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtils = new DbsUtil(dbPoolNames);
        dbsUtils.dbsBeginTransaction();

        //删除积分规则数据信息
        MompSysParamMapper mompSysParamMapper = new MompSysParamMapperImpl();
        //参数类型
        String paramType = "MC_BONUS_POINT_CASHBACK_RULE_VALUE";
        //参数键值
        String paramKey = mcNo;
        returnCode = mompSysParamMapper.deletePointRuleDataInfo(instId, paramType, paramKey);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("删除营销活动积分规则信息失败, RETURN_CODE=<{}>, INST_ID=<{}>, MC_NO=<{}>", returnCode, instId, mcNo);
            dbsUtils.dbsEndTransaction(false);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DELETE_MC_POINTRULE_DATA_ERROR.getRespCode(), RespCodeEnum.DELETE_MC_POINTRULE_DATA_ERROR.getRespDesc());
        }
        dbsUtils.dbsEndTransaction(true);
        //删除临时表营销活动所有信息
        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        returnCode = platBizTmpMapper.deleteTmpMcDataByMcNo(instId, mcNo);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DELETE_TMP_MC_DATA_ERROR.getRespDesc(), returnCode, mcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DELETE_TMP_MC_DATA_ERROR.getRespCode(), RespCodeEnum.DELETE_TMP_MC_DATA_ERROR.getRespDesc());
        }

        /* 正常结束数据库事务 */
        dbsUtil.dbsEndTransaction(true);
    }

    /**
     * 审批通过
     *
     * @param manageCashierCashbackMcRequest 收银员返现类营销活动管理接口请求对象
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/4/7 00:53
     */
    private void auditPassed(ManageCashierCashbackMcRequest manageCashierCashbackMcRequest) throws Exception {

        int returnCode = 0;
        String instId = manageCashierCashbackMcRequest.getHeader().getInstId();
        String mcNo = manageCashierCashbackMcRequest.getMcNo();
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        rglog.debug("INST_ID=<{}>, MC_NO=<{}>", instId, mcNo);

        // 营销活动信息正式表查询
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        TMMcCashierCashbackInfo tmMcCashierCashbackInfo = (TMMcCashierCashbackInfo) mcDetailInfoMapper.selectMcDetailInfo(instId, mcNo, TableNameEnum.T_M_MC_CCB_INFO.getTableNameCode());
        if (null == tmMcCashierCashbackInfo) {
            /* 异常结束数据库事务 */
            rglog.error("查询营销活动信息失败, RETURN_CODE=<{}>, INST_ID=<{}>, MC_NO=<{}>", returnCode, instId, mcNo);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }

        //营销活动信息临时表查询
        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        TMPlatBizTmp platBizTmp = platBizTmpMapper.selectTmpMcInfo(instId, mcNo, TableNameEnum.T_M_MC_CCB_INFO.getTableNameCode());
        if (null == platBizTmp) {
            /* 异常结束数据库事务 */
            rglog.error("查询营销活动信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, tmMcCashierCashbackInfo.getMcNo());
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }

        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        String bizStatus = platBizTmp.getBizStatus();
        if (BizStatusEnum.TMP_STATUS.getBizStatusCode().equals(bizStatus)) {
            // 非正式数据要更新为正式数据
            bizStatus = BizStatusEnum.NORMAL_STATUS.getBizStatusCode();
        }

        // 根据现有营销活动状态判断如更新营销活动状态 */
        String mcStatus;
        if (McStatusEnum.DRAFT.getMcStatusCode().equals(platBizTmp.getMcStatus())) {
            //当前营销活动状态是草稿状态,需要更新营销活动状态为未发布
            mcStatus = McStatusEnum.NOT_PUBLISHED.getMcStatusCode();
        } else {
            //当前营销活动状态不是草稿状态,不需要更新营销活动状态
            mcStatus = platBizTmp.getMcStatus();
        }

        //根据现有审批状态决定如何更新临时表数据
        String oldAuditStatus;
        String newAuditStatus;

        if (AuditStatusEnum.NEW_AUDIT_PROCESSING.getAuditStatusCode().equals(platBizTmp.getAuditStatus())) {
            //新增-审批流程中
            oldAuditStatus = AuditStatusEnum.NEW_AUDIT_PROCESSING.getAuditStatusCode();
            newAuditStatus = AuditStatusEnum.PUBLISH_AUDIT_PROCESSING.getAuditStatusCode();

        } else if (AuditStatusEnum.MODIFY_AUDIT_PROCESSING.getAuditStatusCode().equals(platBizTmp.getAuditStatus())) {
            //修改-审批流程中
            oldAuditStatus = AuditStatusEnum.MODIFY_AUDIT_PROCESSING.getAuditStatusCode();
            newAuditStatus = AuditStatusEnum.PUBLISH_AUDIT_PROCESSING.getAuditStatusCode();

        } else {
            // 营销活动临时数据审批状态异常，不可审批通过
            dbsUtil.dbsEndTransaction(false);
            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.WRONG_TMP_AUDIT_STATUS_TO_PASS_AUDIT_ERROR.getRespDesc(), returnCode, mcNo);
            throw new BizException(RespCodeEnum.WRONG_TMP_AUDIT_STATUS_TO_PASS_AUDIT_ERROR.getRespCode(), RespCodeEnum.WRONG_TMP_AUDIT_STATUS_TO_PASS_AUDIT_ERROR.getRespDesc());
        }

        TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();
        tmPlatBizTmp.setBizStatus(bizStatus);
        tmPlatBizTmp.setMcStatus(mcStatus);
        tmPlatBizTmp.setAuditStatus(newAuditStatus);
        /* 更新临时表审批状态 */
        returnCode = platBizTmpMapper.updateTmpMcInfoByMcNoAndAuditStatus(instId, mcNo, tmPlatBizTmp, oldAuditStatus, globalOprId, globalTimeStamp);
//        // 更新临时表数据
        if (Database.DBS_SUCCESS != returnCode) {
            // 营销活动临时数据审批状态异常，不可审批通过
            dbsUtil.dbsEndTransaction(false);
            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc(), returnCode, mcNo);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }

        //判断如何更新正式表数据,营销活动状态是草稿或未发布状态才需要操作正式表数据
        if (McStatusEnum.DRAFT.getMcStatusCode().equals(tmMcCashierCashbackInfo.getMcStatus()) || McStatusEnum.NOT_PUBLISHED.getMcStatusCode().equals(tmMcCashierCashbackInfo.getMcStatus())) {

            if (McStatusEnum.DRAFT.getMcStatusCode().equals(tmMcCashierCashbackInfo.getMcStatus())) {
                //如果营销活动状态是草稿状态,需要将草稿状态变更为未发布状态,同时将审批状态变更为发布待审批状态
                TMMcCashierCashbackInfo tmMcCashierCashbackInfo1 = new TMMcCashierCashbackInfo();
                tmMcCashierCashbackInfo1.setInstId(instId);
                tmMcCashierCashbackInfo1.setMcNo(mcNo);
                tmMcCashierCashbackInfo1.setMcStatus(McStatusEnum.NOT_PUBLISHED.getMcStatusCode());
                tmMcCashierCashbackInfo1.setAuditStatus(AuditStatusEnum.PUBLISH_AUDIT_PROCESSING.getAuditStatusCode());
                tmMcCashierCashbackInfo1.setLastOprId(globalOprId);
                tmMcCashierCashbackInfo1.setUpdateTime(globalTimeStamp);
                tmMcCashierCashbackInfo1.setAuditRefuseReason(manageCashierCashbackMcRequest.getOprContent());

                returnCode = mcDetailInfoMapper.updateMcStatusForPublishing(tmMcCashierCashbackInfo1, globalTableName);
                if (Database.DBS_SUCCESS != returnCode) {
                    //营销活动审批状态异常，不可审批通过
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc(), returnCode, mcNo);
                    throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                }
            } else {
                /* 如果营销活动状态是未发布状态,需要将审批状态变更为发布-审批流程中 */
                if (AuditStatusEnum.NEW_AUDIT_PROCESSING.getAuditStatusCode().equals(tmMcCashierCashbackInfo.getAuditStatus()) ||
                        AuditStatusEnum.MODIFY_AUDIT_PROCESSING.getAuditStatusCode().equals(tmMcCashierCashbackInfo.getAuditStatus())) {

                    newAuditStatus = AuditStatusEnum.PUBLISH_AUDIT_PROCESSING.getAuditStatusCode();

                } else {
                    /* 营销活动审批状态异常，不可审批通过 */
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.WRONG_AUDIT_STATUS_TO_PASS_AUDIT_ERROR.getRespDesc(), returnCode, mcNo);
                    throw new BizException(RespCodeEnum.WRONG_AUDIT_STATUS_TO_PASS_AUDIT_ERROR.getRespCode(), RespCodeEnum.WRONG_AUDIT_STATUS_TO_PASS_AUDIT_ERROR.getRespDesc());
                }

                /* 更新正式表审批状态 */
                TMMcCashierCashbackInfo tmMcCashierCashbackInfo1 = new TMMcCashierCashbackInfo();
                tmMcCashierCashbackInfo1.setInstId(instId);
                tmMcCashierCashbackInfo1.setMcNo(mcNo);
                tmMcCashierCashbackInfo1.setMcStatus(mcStatus);
                tmMcCashierCashbackInfo1.setAuditStatus(newAuditStatus);
                tmMcCashierCashbackInfo1.setLastOprId(globalOprId);
                tmMcCashierCashbackInfo1.setUpdateTime(globalTimeStamp);

                returnCode = mcDetailInfoMapper.updateMcInfoByMcNoAndAuditStatusAndTableName(tmMcCashierCashbackInfo1, TableNameEnum.T_M_MC_CCB_INFO.getTableNameCode());
                if (Database.DBS_SUCCESS != returnCode) {
                    /* 营销活动审批状态异常，不可审批通过 */
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc(), returnCode, mcNo);
                    throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                }
            }
            //查询商户信息表是否有数据
            McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
            TMMcMchntInfo tmMcMchntInfo = mcMchntInfoMapper.selectMcMchntInfoListCount(tmMcCashierCashbackInfo.getInstId(), tmMcCashierCashbackInfo.getMcNo());
            int mcMchntListSize = Integer.valueOf(tmMcMchntInfo.getRemark5());
            if (mcMchntListSize == CommonConstant.ZERO) {
                //注册定时任务
                timingTask(CommonConstant.CCB_TIME_TASK_NAME, globalTxnDate, "", tmMcCashierCashbackInfo.getInstId(), tmMcCashierCashbackInfo.getMcNo());
            }
        } else {
            // 营销活动状态异常，不可审批通过
            dbsUtil.dbsEndTransaction(false);
            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.WRONG_MC_STATUS_TO_PASS_AUDIT_ERROR.getRespDesc(), returnCode, mcNo);
            throw new BizException(RespCodeEnum.WRONG_MC_STATUS_TO_PASS_AUDIT_ERROR.getRespCode(), RespCodeEnum.WRONG_MC_STATUS_TO_PASS_AUDIT_ERROR.getRespDesc());
        }
        //正常结束数据库事务
        dbsUtil.dbsEndTransaction(true);
    }

    /**
     * 审批拒绝
     *
     * @param manageCashierCashbackMcRequest 收银员返现类营销活动管理接口请求对象
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/4/7 00:53
     */
    private void auditRefused(ManageCashierCashbackMcRequest manageCashierCashbackMcRequest) throws Exception {

        int returnCode = 0;
        String instId = manageCashierCashbackMcRequest.getHeader().getInstId();
        String mcNo = manageCashierCashbackMcRequest.getMcNo();
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        //营销活动信息正式表查询
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        TMMcCashierCashbackInfo tmMcCashierCashbackInfo = (TMMcCashierCashbackInfo) mcDetailInfoMapper.selectMcDetailInfo(instId, mcNo, TableNameEnum.T_M_MC_CCB_INFO.getTableNameCode());
        if (null == tmMcCashierCashbackInfo) {
            // 异常结束数据库事务
            rglog.error("查询营销活动信息失败, RETURN_CODE=<{}>, INST_ID=<{}>, MC_NO=<{}>", returnCode, instId, mcNo);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }

        //营销活动信息临时表查询
        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        TMPlatBizTmp platBizTmp = platBizTmpMapper.selectTmpMcInfo(instId, mcNo, TableNameEnum.T_M_MC_CCB_INFO.getTableNameCode());
        if (null == platBizTmp) {
            //异常结束数据库事务
            rglog.error("查询营销活动信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, tmMcCashierCashbackInfo.getMcNo());
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }

        //开启数据库事务
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        //判断如何更新临时表数据
        if (AuditStatusEnum.NEW_AUDIT_PROCESSING.getAuditStatusCode().equals(platBizTmp.getAuditStatus())) {

            TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();
            tmPlatBizTmp.setBizStatus(platBizTmp.getBizStatus());
            tmPlatBizTmp.setMcStatus(platBizTmp.getMcStatus());
            tmPlatBizTmp.setAuditStatus(AuditStatusEnum.NEW_AUDIT_REJECT.getAuditStatusCode());
            tmPlatBizTmp.setAuditRefuseReason(manageCashierCashbackMcRequest.getOprContent());
            /* 更新临时表审批状态 */
            returnCode = platBizTmpMapper.updateTmpMcInfoByMcNoAndAuditStatus(instId, mcNo, tmPlatBizTmp,
                    AuditStatusEnum.NEW_AUDIT_PROCESSING.getAuditStatusCode(), globalOprId, globalTimeStamp);

            if (Database.DBS_SUCCESS != returnCode) {
                // 营销活动临时数据审批状态异常，不可审批通过
                dbsUtil.dbsEndTransaction(false);
                rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc(), returnCode, mcNo);
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }

        } else if (AuditStatusEnum.MODIFY_AUDIT_PROCESSING.getAuditStatusCode().equals(platBizTmp.getAuditStatus())) {

            TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();
            tmPlatBizTmp.setBizStatus(platBizTmp.getBizStatus());
            tmPlatBizTmp.setMcStatus(platBizTmp.getMcStatus());
            tmPlatBizTmp.setAuditStatus(AuditStatusEnum.MODIFY_AUDIT_REJECT.getAuditStatusCode());
            tmPlatBizTmp.setAuditRefuseReason(manageCashierCashbackMcRequest.getOprContent());
            /* 更新临时表审批状态 */
            returnCode = platBizTmpMapper.updateTmpMcInfoByMcNoAndAuditStatus(instId, mcNo, tmPlatBizTmp,
                    AuditStatusEnum.MODIFY_AUDIT_PROCESSING.getAuditStatusCode(), globalOprId, globalTimeStamp);

            if (Database.DBS_SUCCESS != returnCode) {
                //营销活动临时数据审批状态异常，不可审批通过
                dbsUtil.dbsEndTransaction(false);
                rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc(), returnCode, mcNo);
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }
        } else {
            //营销活动临时数据审批状态异常，不可审批通过
            dbsUtil.dbsEndTransaction(false);
            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.WRONG_TMP_AUDIT_STATUS_TO_REFUSE_AUDIT_ERROR.getRespDesc(), returnCode, mcNo);
            throw new BizException(RespCodeEnum.WRONG_TMP_AUDIT_STATUS_TO_REFUSE_AUDIT_ERROR.getRespCode(), RespCodeEnum.WRONG_TMP_AUDIT_STATUS_TO_REFUSE_AUDIT_ERROR.getRespDesc());
        }

        //判断如何更新正式表数据
        if (McStatusEnum.DRAFT.getMcStatusCode().equals(tmMcCashierCashbackInfo.getMcStatus()) ||
                McStatusEnum.NOT_PUBLISHED.getMcStatusCode().equals(tmMcCashierCashbackInfo.getMcStatus())) {
            /* 更新正式表审批状态 */
            TMMcCashierCashbackInfo tmMcCashierCashbackInfo1 = new TMMcCashierCashbackInfo();
            tmMcCashierCashbackInfo1.setInstId(instId);
            tmMcCashierCashbackInfo1.setMcNo(mcNo);
            tmMcCashierCashbackInfo1.setMcStatus(tmMcCashierCashbackInfo.getMcStatus());
            tmMcCashierCashbackInfo1.setAuditRefuseReason(manageCashierCashbackMcRequest.getOprContent());
            tmMcCashierCashbackInfo1.setLastOprId(globalOprId);
            tmMcCashierCashbackInfo1.setUpdateTime(globalTimeStamp);
            tmMcCashierCashbackInfo1.setPublishRefuseReason(tmMcCashierCashbackInfo.getPublishRefuseReason());

            if (AuditStatusEnum.NEW_AUDIT_PROCESSING.getAuditStatusCode().equals(tmMcCashierCashbackInfo.getAuditStatus())) {
                //设置审批状态为 新增——审批拒绝
                tmMcCashierCashbackInfo1.setAuditStatus(AuditStatusEnum.NEW_AUDIT_REJECT.getAuditStatusCode());
                returnCode = mcDetailInfoMapper.updateMcInfoByMcNoAndAuditStatusAndTableName(tmMcCashierCashbackInfo1, TableNameEnum.T_M_MC_CCB_INFO.getTableNameCode());

                if (Database.DBS_SUCCESS != returnCode) {
                    /* 营销活动审批状态异常，不可审批拒绝 */
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc(), returnCode, mcNo);
                    throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                }

            } else if (AuditStatusEnum.MODIFY_AUDIT_PROCESSING.getAuditStatusCode().equals(tmMcCashierCashbackInfo.getAuditStatus())) {
                //设置审批状态为 修改——审批拒绝
                tmMcCashierCashbackInfo1.setAuditStatus(AuditStatusEnum.MODIFY_AUDIT_REJECT.getAuditStatusCode());
                returnCode = mcDetailInfoMapper.updateMcInfoByMcNoAndAuditStatusAndTableName(tmMcCashierCashbackInfo1, TableNameEnum.T_M_MC_CCB_INFO.getTableNameCode());
                if (Database.DBS_SUCCESS != returnCode) {
                    /* 营销活动审批状态异常，不可审批拒绝 */
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc(), returnCode, mcNo);
                    throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                }
            } else {
                //营销活动审批状态异常，不可审批通过
                dbsUtil.dbsEndTransaction(false);
                rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.WRONG_AUDIT_STATUS_TO_REFUSE_AUDIT_ERROR.getRespDesc(), returnCode, mcNo);
                throw new BizException(RespCodeEnum.WRONG_AUDIT_STATUS_TO_REFUSE_AUDIT_ERROR.getRespCode(), RespCodeEnum.WRONG_AUDIT_STATUS_TO_REFUSE_AUDIT_ERROR.getRespDesc());
            }

        } else {
            //营销活动状态异常，不可审批通过
            dbsUtil.dbsEndTransaction(false);
            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.WRONG_MC_STATUS_TO_REFUSE_AUDIT_ERROR.getRespDesc(), returnCode, mcNo);
            throw new BizException(RespCodeEnum.WRONG_MC_STATUS_TO_REFUSE_AUDIT_ERROR.getRespCode(), RespCodeEnum.WRONG_MC_STATUS_TO_REFUSE_AUDIT_ERROR.getRespDesc());
        }

        //正常结束数据库事务
        dbsUtil.dbsEndTransaction(true);
    }

    /**
     * 注册定时任务
     *
     * @param taskName   任务名称
     * @param settleDate 清算日期 不上送 默认当前日期
     * @param regTime    执行日期 不上送 立即执行
     * @param taskBatch  批次号后五位清算日期内唯一
     * @param taskParam  营销活动编号
     * @throws Exception
     */
    private void timingTask(String taskName, String settleDate, String regTime, String taskBatch, String taskParam) throws Exception {
        taskBatch = taskBatch.concat(MompToolUtil.getAppoint(MompDateUtil.getTime(), 0, 5));
        rglog.info("任务名称<{}> 清算日期<{}> 执行时间<{}> 批次号<{}> 营销活动编号<{}>", taskName, settleDate, regTime, taskBatch, taskParam);
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID, MOMP_RBDP_ADDRESS, MOMP_RBDP_REGISTER_ADDRESS);
        if (null == sysParam) {
            rglog.error("获取批量任务注册地址失败！");
            throw new BizException(RespCodeEnum.FAILED_TO_GET_RBDP_REGISTER_ADDRESS.getRespCode(), RespCodeEnum.FAILED_TO_GET_RBDP_REGISTER_ADDRESS.getRespDesc());
        }
        //批量注册地址
        String rbdpserver = sysParam.getParamValue();
        RealTimeRegisterClient a = RbdpClient.getIntance1(rglog, rbdpserver);

        int ret = a.registerTask(taskName, settleDate, settleDate.concat(DateUtil.getCurrentTime()), taskBatch, taskParam);
        rglog.info("实时任务注册返回：ret {}", ret);
        String result = "";
        if (0 != ret) {
            result = "注册失败: " + RbdpClient.getIntance1(rglog, rbdpserver).getError();
            rglog.error("实时任务注册返回：ret {}", result);
            throw new BizException(RespCodeEnum.FAILED_TO_TIME_TASK.getRespCode(), RespCodeEnum.FAILED_TO_TIME_TASK.getRespDesc());
        } else {
            result = "注册成功.";
            rglog.info("实时任务注册返回：ret {}", result);
        }
    }
}
